﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Web.Security;
using System.Web.UI;
using BlueMarineWebClient.DO;

namespace BlueMarineWebClient.Account
{
    public partial class Register : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lblTitle.Text = "Create a New Account";
            }
        }

        public string GetConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
        }


        public static string CreateRandomPassword(int passwordLength)
        {
            const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
            var chars = new char[passwordLength];
            var rd = new Random();

            for (int i = 0; i < passwordLength; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }

            return new string(chars);
        }

        protected void CreateUserButton_Click(object sender, EventArgs e)
        {
            bool sex = rbMale.Checked;


            string account;
            string password = CreateRandomPassword(6);
            bool result = ServiceBool.ExService.CustomerAdd(out account, txtIN.Text, txtFullname.Text, txtPhone.Text,
                                                            txtEmail.Text,
                                                            sex);
            if (result)
            {
                Membership.CreateUser(account, password);

                var msg = new MailMessage();

                msg.To.Add(new MailAddress(txtEmail.Text));
                msg.From = new MailAddress("BlueMarineHotel@gmail.com");
                msg.Subject = "Account Information at BlueMarineHotel.com";
                msg.Body = "Your Username: <b>" + account + "</b> and Password: <b>" + password +"</b>";

                msg.IsBodyHtml = true;

                msg.Priority = MailPriority.Normal;

                var smtp = new SmtpClient
                               {
                                   Host = "smtp.gmail.com",
                                   Port = 587,
                                   EnableSsl = true,
                                   Credentials = new NetworkCredential("bluemarinehotel@gmail.com", "12345hotel")
                               };
                smtp.Send(msg);


                Response.Redirect("/Web/redirect.aspx?mess=registersuccess");
            }
            else
            {
                Response.Redirect("/Web/redirect.aspx?mess=registerfail");
            }
        }
    }
}